//
//  MineViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/8/20.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

class MineViewController: KMViewController {
    
    fileprivate let cellId = "mineCell"

    var headView : MineHeadView! // 头部视图
    
    fileprivate lazy var titleLabel = UILabel() //头部标题
    
    fileprivate lazy var navBarAlpha : CGFloat = 0 //导航栏当前透明度
    
    fileprivate lazy var navBarHeight = StatusBarAddNavBarHeight //导航栏加状态栏高度
   
    var tableView : UITableView!
    
    var dataSource = [myTransaction,creditCardActivation,creditCardWithdrawal,repaymentReminder,personalTaxation,nearbyBank,commentsAndFeedback,setting] //个人数据
    var imageArray = [#imageLiteral(resourceName: "transaction"),#imageLiteral(resourceName: "card_active"),#imageLiteral(resourceName: "card_raise"),#imageLiteral(resourceName: "remind"),#imageLiteral(resourceName: "tax"),#imageLiteral(resourceName: "nearBank"),#imageLiteral(resourceName: "mail"),#imageLiteral(resourceName: "setting")] //图片
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.navigationBar.isTranslucent = true
        
        addTitleView()
        createTableView()
    }
    
    //MARK: 添加头部标题
    fileprivate func addTitleView() {
        
        titleLabel.text = mine_title
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 18)
        titleLabel.alpha = 0
        self.navigationItem.titleView = titleLabel
        
    }
    
    //MARK: 添加tableView
    fileprivate func createTableView() {
        
        headView = MineHeadView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 350)))
        headView.mineDelegate = self
        
        //头像添加点击事件
        let tapGestrue = UITapGestureRecognizer.init(target: self, action: #selector(changeAvatar))
        headView.headImageView.isUserInteractionEnabled = true
        headView.headImageView.addGestureRecognizer(tapGestrue)
        
        
        let footerView = UIView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 40)))
        footerView.backgroundColor = UIColor.white
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableHeaderView = headView
        tableView.tableFooterView = footerView
        tableView.rowHeight = RATIO_H(maxNum: 40)
        tableView.register(MineCell.self, forCellReuseIdentifier: cellId)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: -StatusBarAddNavBarHeight, left: 0, bottom: 0, right: 0))
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        self.navigationController?.navigationBar.isUserInteractionEnabled = false
        //导航栏颜色透明
    self.navigationController?.navigationBar.setBackgroundImage(UIImage.imageWithColor(UIColor.red.withAlphaComponent(self.navBarAlpha)), for: .default)
        //去掉透明后导航栏下边的黑线
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        if KMTool.isSignIn() && headView != nil && KMTool.stringForEnumKey(.avatar) != "" {
            if let avatar = KMTool.stringForEnumKey(.avatar) {
                headView.headImageView.image = KMTool.base64ToImage(base: avatar)
                headView.redView.layer.contents = KMTool.blurryImage(image: headView.headImageView.image!).cgImage
                headView.redView.backgroundColor = UIColor.clear
            }
            
            if KMTool.stringForEnumKey(.userName) != "" {
                headView.nameLabel.text = KMTool.stringForEnumKey(.userName)
            }else{
                headView.nameLabel.text = KMTool.stringForEnumKey(.phone)
            }
            
        }else if !KMTool.isSignIn() && headView != nil {
            headView.headImageView.image = #imageLiteral(resourceName: "avatar_default")
            headView.redView.layer.contents = nil
            headView.nameLabel.text = logInNow
            headView.redView.backgroundColor = UIColor.red
        }

    }
    
    //MARK: 页面消失时恢复导航栏
    override func viewDidDisappear(_ animated: Bool) {
        
//        self.navigationController?.navigationBar.isUserInteractionEnabled = true
        self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        self.navigationController?.navigationBar.shadowImage = nil
        
    }
    
    //MARK: 修改用户头像
    @objc fileprivate func changeAvatar() {
        
        if !KMTool.isSignIn() {
            let signInVC = SignInViewController()
            signInVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(signInVC, animated: true)
        }else{
            let editVC = EditViewController()
            editVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(editVC, animated: true)
        }
        
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension MineViewController : UITableViewDelegate,UITableViewDataSource {
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? MineCell
        cell?.titleLabel.text = dataSource[indexPath.row]
        cell?.iconImageView.image = imageArray[indexPath.row]
        cell?.accessoryType = .disclosureIndicator
        
//        switch indexPath.row {
//        case 1:
//            break
//        default:
//            break
//        }
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        switch indexPath.row {
        case 0: //我的交易
            if !KMTool.isSignIn() {
                let signInVC = SignInViewController()
                signInVC.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(signInVC, animated: true)
                return
            }
            let recordVC = RecordViewController.init(title: dataSource[indexPath.row])
            recordVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(recordVC, animated: true)
        case 1: //信用卡激活
            let serviceVC = ServiceViewController.init(urlString: "/mobile/activation", title: creditCardActivation)
            serviceVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(serviceVC, animated: true)
        case 2: //信用卡提额
            let improveVC = ImproveViewController.init(urlString: "/mobile/forehead", title: liftingCheats)
            improveVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(improveVC, animated: true)
        case 3:
            if KMTool.isSignIn() {
                let repaymentVC = RepaymentViewController()
                repaymentVC.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(repaymentVC, animated: true)
            }else{
                let signInVC = SignInViewController()
                signInVC.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(signInVC, animated: true)
                return
            }
            
        case 5: //附近银行
            let bankVC = BankViewController()
            bankVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(bankVC, animated: true)
        case 6: //意见与反馈
            let helpVC = HelpViewController()
            helpVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(helpVC, animated: true)
        case 7: //设置
            let setVC = SetViewController()
            setVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(setVC, animated: true)
        default:
            break
        }
    }
    
    //MARK: 通过tableView偏移量改变导航栏透明度
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
//        MyLog(scrollView.contentOffset.y)

        var alpha = (scrollView.contentOffset.y + StatusBarAddNavBarHeight) / 30
        if alpha >= 1 {
            alpha = 0.99
        }
        
        let image = UIImage.imageWithColor(UIColor.red.withAlphaComponent(alpha))
        self.titleLabel.alpha = alpha
        self.navigationController?.navigationBar.setBackgroundImage(image, for: .default)

        self.navBarAlpha = alpha
        
    }
}

extension MineViewController : MineHeadViewDelegate {
    
    //MARK: 选择头部操作类型
    func selectService(index: Int) {
        
        switch index {
        case 0:
           let handleVC = HandleViewController.init()
           handleVC.hidesBottomBarWhenPushed = true
           self.navigationController?.pushViewController(handleVC, animated: true)
        case 1:
            if KMTool.isSignIn() {
                let packageVC = PackageViewController()
                packageVC.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(packageVC, animated: true)
            }else{
                let signInVC = SignInViewController()
                signInVC.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(signInVC, animated: true)
                return
            }
            
        default:
            break
        }
    }
    
}


